/*******************************************************************************
 * Copyright (c) 2011 Technische Universität Darmstadt
 * 					  Fachbereich Informatik
 * 					  Theoretische Informatik - Kryptographie und Computeralgebra
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 ******************************************************************************/

/*
 *	Some Imports. Don't know if they are still all necessary.
 */
var info = Components.classes["@mozilla.org/xre/app-info;1"]
.getService(Components.interfaces.nsIXULAppInfo);

if(info.version.charAt(0)<5){
	Components.utils.import("resource://app/modules/errUtils.js"); // not comp w TB5
	Components.utils.import("resource://app/modules/gloda/utils.js"); //not tb5
	Components.utils.import("resource://app/modules/gloda/gloda.js"); //not tb5
}
Components.utils.import("resource://gre/modules/iteratorUtils.jsm");
Components.utils.import("resource:///modules/MailUtils.js");
Components.utils.import("resource:///modules/gloda/mimemsg.js");
Components.utils.import("resource:///modules/gloda/noun_mimetype.js");

if(info.version.charAt(0)>=5){
	Components.utils.import("resource://gre/modules/AddonManager.jsm"); //needed!
	Components.utils.import("resource://gre/modules/Services.jsm");
}

var stringBundlef;

window.addEventListener("load", function(){
	stringBundlef = document.getElementById("cryptoBirdStringBundle");
}, false);

/**
 * this function checks the decryption of the subject and the content and decrypt both if necessary.
 */
function checkdecryption(){
	//check if there is an encrypted mail
	var win = Components.classes["@mozilla.org/appshell/window-mediator;1"].
	getService(Components.interfaces.nsIWindowMediator).
	getMostRecentWindow("mail:3pane");
	var msg = win.gFolderDisplay.selectedMessage;
	var header = msg.QueryInterface(Components.interfaces.nsIMsgDBHdr);
	var body = getMessageBody(header);
	var uri = header.folder.getUriForMsg(header);

	var endEncrypted = "-----END PGP MESSAGE-----";
	var startEncrypted = "-----BEGIN PGP MESSAGE-----";
	if (body.indexOf(startEncrypted) != -1 && body.indexOf(endEncrypted) != -1) {
		//lookup URI in DB
		document.getElementById('item-description').value= win.TheChasingDragon.cryptoBirdJava.getMessageBodyByURI(uri);
	}else{
		myDump('content does not contain PGP block');
	}
	var dbSubject = win.TheChasingDragon.cryptoBirdJava.decryptSubject(uri);
	if(dbSubject != "---ERROR---" && dbSubject != ""){
		// title ändern: look@ DOM-tree
		document.getElementById('item-title').value= dbSubject;
		refreshTitle();
	}

}
/**
 * returns messageBody to a given messageHeader
 */
function getMessageBody(aMessageHeader) {
	let messenger = Components.classes["@mozilla.org/messenger;1"].createInstance(Components.interfaces.nsIMessenger);
	let listener = Components.classes["@mozilla.org/network/sync-stream-listener;1"].createInstance(Components.interfaces.nsISyncStreamListener);
	let uri = aMessageHeader.folder.getUriForMsg(aMessageHeader);
	messenger.messageServiceFromURI(uri).streamMessage(uri, listener, null, null, false, "");
	let folder = aMessageHeader.folder;
	var result = folder.getMsgTextFromStream(listener.inputStream,
			aMessageHeader.Charset,
			65536,
			32768,
			false,
			true,
			{ });
	return result;
}



function onAboutCBMenuItemCommand(){
	var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
	prompts.alert(null, stringBundlef.getString("cryptoBird.compose.infowindowtitle"),stringBundlef.getString("cryptoBird.calendar.info"));

}

function onEncEventMenuItemCommand(){
	checkdecryption();
}

function myDump(aMessage) {
	var consoleService = Components.classes["@mozilla.org/consoleservice;1"]
	.getService(Components.interfaces.nsIConsoleService);
	consoleService.logStringMessage("CrytoBird: " + aMessage);
}

/**
 * refreshes window title (manual input from user needed, so we send blank and del as keyboard events)
 */
function refreshTitle(){
	sendKeyEvent(32);
	sendKeyEvent(8);
}

/**
 * function needed for workaround to update title of window: this function inserts the character c into the title which causes the window title to change 
 * @param c  the character which should be inserted
 */

function sendKeyEvent(c){
	var e = document.createEvent("KeyboardEvent");
	e.initKeyEvent('keypress', true, true, null, false, false, false, false, c, c);

	var obj = document.getElementById("item-title");
	obj.inputField.dispatchEvent(e);
}



